package com.hiwan.system.service.role;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hiwan.framework.dao.annotation.LogRecord;
import com.hiwan.platform.utils.StringUtils;
import com.hiwan.system.cache.DictCacheService;
import com.hiwan.system.cache.SysCacheService;
import com.hiwan.system.common.base.GenericService;
import com.hiwan.system.dao.role.RoleDao;
import com.hiwan.system.dao.user.UserDao;
import com.hiwan.system.pojo.DictEntry;
import com.hiwan.system.pojo.MenuInfo;
import com.hiwan.system.pojo.RoleInfo;
import com.hiwan.system.pojo.RoleMenuInfo;
import com.hiwan.system.pojo.TreeNode;
import com.hiwan.system.service.menu.MenuPojo2Map;
import com.hiwan.system.service.menu.MenuService;
import com.hiwan.system.util.PageUtil;
import com.hiwan.system.util.UserCacheUtils;


/**
 * 
 * Datetime   ： 2016年1月13日 下午4:17:17<br>
 * Title      :  RoleService.java<br>
 * Description:   角色服务<br>
 * Company    :  hiwan<br>
 * @author cbj
 *
 */
@Service
@Transactional
public class RoleService extends GenericService<RoleDao, RoleInfo, String>{
	
	@Autowired
	private UserDao userDao;
	@Autowired
	private MenuService menuService;
	@Autowired
	private DictCacheService dictCacheService;
	@Autowired
	private SysCacheService sysCacheService;
	
	/**
	 * 获取角色信息列表
	 * @return
	 */
	public List<RoleInfo> getRoleDetailList() {
		List<RoleInfo> roleList = null;
		roleList = dao.selectListPage(new RoleInfo(),PageUtil.getRowBounds());
		return roleList;
	}
	
	/**
	 * 获取已启用的角色信息列表
	 */
	public List<RoleInfo> getEnableRoleList(RoleInfo roleInfo) {
		List<RoleInfo> roleList = null;
		//是否允许展示同级角色 yes--是，no--否,当此字段为空时，默认允许
		String isAllow = sysCacheService.getSysParameter("init_role", "*", "*").getParam1();
		if(StringUtils.isNotEmpty(isAllow)){
			isAllow = isAllow.replace(" ", "");
			if(StringUtils.isNotEmpty(isAllow)){
				isAllow = isAllow.toLowerCase();
			}
			roleInfo.setIsAllow(isAllow);
		}
		RoleInfo role = new RoleInfo();
		role.setRoleStatus("1");

		roleList = dao.selectListPage(roleInfo,PageUtil.getRowBounds());
		return roleList;
	}
	
	/**
	 * 获取具体角色的详细信息
	 * @param roleId
	 * @return
	 */
	public RoleInfo getRoleDetailInfo(String roleId) {
		RoleInfo  roleInfo = dao.selectOne(roleId);
		return roleInfo;
	}
	/**
	 * 根据按逗号分隔的角色id，得到角色的详细集合信息。
	 * @author 李仕波
	 * @date 2016年1月25日 下午5:33:22
	 * @version hiwan3.0
	 */
	public List<RoleInfo> getRoleListByComma(String roleIds) {
		List<RoleInfo> roleList=new ArrayList<RoleInfo>();
		String[] roles=roleIds.split(",");
		for(String r:roles){
			if(StringUtils.isNotBlank(r)){
				RoleInfo  roleInfo = dao.selectOne(r);
				if(roleInfo!=null){
					roleList.add(roleInfo);
				}
			}
		}
		return roleList;
	}
	
	/**
	 * 获取每个人的默认菜单
	 * @return
	 */
	public String getInitMenu(){
		String initMenu="";
		Map<String, Object> tempMenu = MenuPojo2Map.getMap(sysCacheService.getSysParameter("init_menu", "*", "*"));
		for(int i=1;i<8;i++){
			if(i!=5 && i!=6){
				String temp = (String) tempMenu.get("Param"+i);	
				if(StringUtils.isNotEmpty(temp)){
					initMenu+=temp+"|";
				}
			}
		}
		return initMenu;
	}
	
	/**
	 * 新增角色
	 */
	@Override
	@LogRecord
	public int add(RoleInfo roleInfo) {
		int result = 0;
		String roleName = roleInfo.getRoleName();
		roleName = roleName.replace(" ", "");
		roleInfo.setRoleName(roleName);
		int temp = getRoleNameCount(roleInfo);
		if(temp == 1){
			result = 2; //已存在同名角色
		}
		else{
			result = dao.insert(roleInfo);
			String createUser=roleInfo.getCreateBy();
			if(result==1 && (roleInfo.getRoleStatus()).equals("1")){
				roleInfo=dao.selectNewRole(createUser);
				this.setRoleDict("insert",roleInfo);
			}
			UserCacheUtils.removeCache(UserCacheUtils.CACHE_ROLE_LIST);
		}
		return result;
	}
	

	/**
	 * 修改用户信息
	 */
	@Override
	@LogRecord
	public int modify(RoleInfo roleInfo) {
		int result = 0;
		String roleName = roleInfo.getRoleName();
		roleName = roleName.replace(" ", "");
		roleInfo.setRoleName(roleName);
		int temp = getRoleNameCount(roleInfo);
		if(temp == 1){
			result = 2; //已存在同名角色
		}
		else{
			result = dao.update(roleInfo);
			if(result==1 && (roleInfo.getRoleStatus()).equals("1")){
				this.setRoleDict("update",roleInfo);
			}
			if(result==1 && !(roleInfo.getRoleStatus()).equals("1")){
				this.setRoleDict("delete",roleInfo);
			}
			UserCacheUtils.clearAllUserCache();
		}
		return result;
	}
	
	/**
	 * 删除角色信息，并更新相关用户的信息
	 */
	@Override
	@LogRecord
	public int remove(String roleId) {
		
		RoleInfo roleInfo=dao.selectOne(roleId);
		if(StringUtils.equals("1", roleInfo.getRoleStatus())){
			return 0;
		}
		int result = dao.delete(roleId);//清除hw_role表中数据
		//查询是否是新建菜单
		List<RoleMenuInfo> llist=dao.selectRoleMenuInfo(roleId);
		if(llist!=null&&llist.size()>0){
			result=this.dao.deleteRoleMenu(roleId);
		}
		
		this.setRoleDict("delete", roleInfo);//清除字典项中的值
		/**
		 * 更新所有HW_USER_RELATION中所有的角色信息
		 */
		/*List<UserRelation> selectUserList=userDao.selectUserRelations("");
		
		for (UserRelation s : selectUserList) {
			String roleArr[]=s.getRoleIdstr().split(",");
		    List<String> rolesss= new ArrayList<String>(Arrays.asList(roleArr)); 
		    	if(rolesss.contains(roleId)){
		    		rolesss.remove(roleId);
					String newRoleIdstr=rolesss.toString().replace("[", "").replace("]", "").replaceAll("\\s*", "");
					s.setRoleIdstr(newRoleIdstr);
					result=userDao.updateUserRelation(s);
				}
		}*/
		UserCacheUtils.clearAllUserCache();
		return result;
	}

	/**
	 * 确定是否有同名角色
	 * @param roleInfo
	 * @return
	 */
	public int getRoleNameCount(RoleInfo roleInfo){
		RoleInfo  roleInfo2 = (RoleInfo) dao.selectRoleCount(roleInfo);
		int roleCount = 0;
		if(roleInfo2!=null){
			roleCount = roleInfo2.getRoleCount();
			String temp1 = roleInfo.getRoleId();
			String temp2 = roleInfo2.getRoleId();
			if(!temp1.equals(temp2)&& roleCount>0){
				roleCount=1;
			}
			if(!temp1.equals(temp2)&& roleCount==0){
				roleCount=0;
			}
			if(temp1.equals(temp2)&& roleCount==1){
				roleCount=0;
			}
			if(temp1.equals(temp2)&& roleCount>1){
				roleCount=1;
			}
		}
		return roleCount;
	}
	
	/**
	 * 更新角色字典项
	 * @param doType
	 * @param roleInfo
	 */
	public void setRoleDict(String doType,RoleInfo roleInfo) {
		//对字典项的实体进行赋值
		DictEntry dictEntry =new DictEntry();
		dictEntry.setDictType("D00006");
		dictEntry.setDictCode(roleInfo.getRoleId());
		dictEntry.setDictValue(roleInfo.getRoleName());
		String doUser=roleInfo.getCreateBy();
		if(StringUtils.isEmpty(doUser)){
			doUser=roleInfo.getUpdateBy();
		}		
		dictEntry.setUpdateBy(doUser);
		// 角色新增、修改
		if("delete".equals(doType)){// 删除
			 dictCacheService.removeDictEntry(dictEntry);
	    }else{//新增、修改
	    	 dictCacheService.setDictEntry(dictEntry);
	    }
	}
	
	/**
	 * 
	 *保存用户角色。
	 *如果只有父节点，那么其所有子节点也选中了。有一个子节点选中，只保存选中的子节点。
	 * @author lsb
	 * @since  2015-11-16 上午10:04:44
	 * @version hiwan 3.0	
	 * @return
	 */
	public int saveRoleMenu(RoleInfo roleInfo, RoleMenuInfo roleMenuInfo) {
		String roleId = roleMenuInfo.getRoleId();
		String menuId = roleMenuInfo.getMenuId();
		int result = 0;
       //如果没有选中菜单
		if(StringUtils.isEmpty(menuId)){
			List<RoleMenuInfo> list=dao.selectRoleMenuInfo(roleId);
			if(list==null||list.isEmpty()){
				return result=1;
			}else{
				result=this.dao.deleteRoleMenu(roleInfo.getRoleId());
				return result>0?1:0;
			}
			
		}else{
		// String [] menuid=menuId.split("\\|"); version 2.0
			String[] menuIds = menuId.split(",");
			List<String> menuList = Arrays.asList(menuIds);// 要保存的菜单信息[00004,00020,00022,00024]
			List<String> menuListNew= new ArrayList<String>(menuList);
			// 确保menuList中只有父菜单,没有子菜单
			for (String mId : menuList) {
				MenuInfo info = menuService.getMenuInfo(mId);
				if (info.getIsLeaf().equals("0")) {// 父节点
					List<String> infoList = menuService.obtainMenuIdList(info.getMenuId());
					// boolean hasChildren=infoList.retainAll(menuList);//两个集体的交集
					boolean hasChildren = Collections.disjoint(menuList, infoList);// 两个集体的交集
					if (hasChildren) {
						menuListNew.addAll(infoList);
					}
				}
			}
			if (StringUtils.isNotEmpty(roleId)) {
				this.dao.deleteRoleMenu(roleInfo.getRoleId());
				if (StringUtils.isEmpty(menuId)) {
					result = 1;
				}
				if (StringUtils.isNotEmpty(menuId)) {
					for (String string : menuListNew) {
						roleMenuInfo.setMenuId(string);
						result = dao.insertRoleMenu(roleMenuInfo);
					}
				}
			}
			UserCacheUtils.clearAllUserCache();
			return result;
		}
	}
	
	/**
	 * 查询菜单树并显示当前角色拥有的权限菜单
	 * @param roleId
	 * @return
	 */
	public List<TreeNode> getRoleMenuNodes(String roleId){
		List<TreeNode> nodeList = new ArrayList<TreeNode>();
		List<TreeNode> menuList = menuService.getAllMenuList();
		List<String> roleMenuIdList =this.getRoleMenuList(roleId);
		List<String> initMenuList = this.getInitRoleMenu(roleId);
		for(TreeNode node:menuList){
			String meunId =node.getId();
			if(roleMenuIdList !=null && roleMenuIdList.size()>0){
			for(String roleMenuId:roleMenuIdList){
				if(meunId.equals(roleMenuId)){
					node.setIsChecked("true");
					System.out.println("roleMenuId==="+roleMenuId);
				}
			}
			}
			if(initMenuList !=null && initMenuList.size()>0){
			for(String initMenuId:initMenuList){
				if(meunId.equals(initMenuId)){
					node.setIsChecked("true");
					node.setDisabled("true");
					System.out.println("initMenuId==="+initMenuId);
				}
			}
			}
			nodeList.add(node);
		}
		
		return nodeList;
		
	}
	/**
	 * 获取角色的权限菜单
	 * @param roleId
	 * @return
	 */
	public List<String> getRoleMenuList(String roleId) {
		List<String> roleMenuIdList = new ArrayList<String>();
		List<RoleMenuInfo> roleMenuList = dao.selectRoleMenuInfo(roleId);
		//角色没有菜单时
		if(roleMenuList==null||roleMenuList.isEmpty()){
			return null;
		}
		for(RoleMenuInfo o : roleMenuList){
				roleMenuIdList.add(o.getMenuId());
		}
		return roleMenuIdList;
	}
	/**
	 * 获取角色的默认必选菜单
	 * @param roleInfo
	 * @return
	 */
	public List<String> getInitRoleMenu(String roleId){
		List<String> initRoleList=new ArrayList<String>();
		Map<String, Object> roleMenu = MenuPojo2Map.getMap(sysCacheService.getSysParameter("role_menu", "*", "*"));
		for(int j=1;j<8;j++){
			if(j!=5 && j!=6){
				String temp = (String) roleMenu.get("Param"+j);	
				if(StringUtils.isNotEmpty(temp)){
					String [] var = temp.split(":");
					if(var[0].equals(roleId)){
						initRoleList.add(var[1]);
					}
				}
			}
		}
		return initRoleList;
	}
}